﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace wUniAppPCL.IO
{
  public interface IwStorage
  {
    Stream OpenStream(string name, bool onlyRead);
    void SaveStream(Stream stream, string name);
  }

  public abstract class wBaseStorage : IwStorage
  {
    public wBaseStorage()
    {
      TextEncoding = Encoding.UTF8;
    }

    
    public Encoding TextEncoding { get; set; }

    public abstract Stream Read(string name, bool onlyRead);
    public abstract void Write(Stream stream, string name);
    public abstract bool Exist(string name);
    public abstract void Delete(string name);

    public Stream OpenStream(string name, bool onlyRead)
    {
      if (Exist(name) || !onlyRead)
      {
        return Read(name, onlyRead);
      }
      else throw new Exception(name + " not exist.");
    }

    public string LoadString(string name)
    {
      var res = "";
      Stream stream = OpenStream(name, true);
      stream.Position = 0;
      using (StreamReader reader = new StreamReader(stream, TextEncoding))
      {
        res = reader.ReadToEnd();
      }
      return res;
    }

    public void SaveStream(Stream stream, string name)
    {
      if (Exist(name))
      {
        Delete(name);
      }
      Write(stream, name);
    }
    public void SaveString(string sourceText, string name)
    {
      using (MemoryStream ms = new MemoryStream())
      {
        var bytes = TextEncoding.GetBytes(sourceText);
        ms.Write(bytes, 0, bytes.Length);
        SaveStream(ms, name); 
      }
    }

  }
}
